package handler
import (
	"golang.org/x/net/context"
	oauth2 "git.oschina.net/fanbuchi/xgggh/oauth2/proto/oauth2"
	 "git.oschina.net/fanbuchi/xgggh/errs"
	oauth2Service "git.oschina.net/fanbuchi/xgggh/oauth2/service"
	"git.oschina.net/fanbuchi/xgggh/oauth2/model"
	"git.oschina.net/fanbuchi/xgggh/oauth2/service"
	"git.oschina.net/fanbuchi/xgggh/oauth2/tokentypes"
)
//password grant
func password(ctx context.Context, req *oauth2.TokenReq, rsp *oauth2.TokenRsp)error {
	// Get the scope string
	scope:=req.Scope
	if scope=="" {
		return errs.ScopeNotFound
	}
	if req.ClientId=="" {
		return errs.ClientNotFound
	}
	if req.ClientSecret=="" {
		return errs.ClientSecretNotFound
	}

	// Authenticate the user
	_account,e:=oauth2Service.Password(req.UserName,req.Password)
	if e != nil {
		// For security reasons, return a general error message
		return e
	}

	// Log in the user
	_client,err:=service.ClientSearchByClientId(req.ClientId)
	if err !=nil{
		return err
	}
	//key|secret 非法
	if _client==nil||_client.Secret!=req.ClientSecret {
		return errs.ClientInvalid
	}
	accessToken, refreshToken, err := oauth2Service.UserLogon(_client, _account, scope)
	if err != nil {
		return  err
	}

	// Create response
	rsp.Data=&oauth2.Token{AccountId:int64(_account.ID),
		AccessToken:accessToken.Token,
		ExpiresIn:model.GetOauthConfig().AccessTokenLifetime,
		TokenType:tokentypes.Bearer,
		RefreshToken:refreshToken.Token,
		Scope:accessToken.Scope,
	}

	return err
}
